package com.bosssoft.cloud.wechat.infrastructure.factory;


import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

import java.io.IOException;
import java.util.Properties;

/**
 * 解析yaml,yml文件factory
 * <p>
 * 自定义PropertySourceFactory，进行了对jdk1.7的springboot1.x适配
 *
 * @author wcy create on 2021/5/26 17:11 下午
 */
public class YamlAndPropertySourceFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        if (resource == null) {
            return super.createPropertySource(name, null);
        }
        Resource resourceResource = resource.getResource();
        if (!resourceResource.exists()) {
            return new PropertiesPropertySource(null, new Properties());
        } else if (resourceResource.getFilename().endsWith(".yml") || resourceResource.getFilename().endsWith(".yaml")) {
            return new YamlPropertySourceLoader().load(resourceResource.getFilename(), resourceResource, null);
        }
        return super.createPropertySource(name, resource);
    }
}

